package com.ktjy.controller;

import com.alibaba.fastjson.JSON;
import com.ktjy.pojo.StorageRecord;
import com.ktjy.pojo.Supplier;
import com.ktjy.pojo.SysRole;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.StorageRecordService;
import com.ktjy.service.SupplierServlet;
import com.ktjy.service.SysRoleService;
import com.ktjy.service.SysUserService;
import com.ktjy.ulits.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*
 *sys/supplier/toAdd
 * d/sys/user/toAdd
 *
 * */

@Controller
public class CVSController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SupplierServlet supplierServlet;
    @Autowired
    StorageRecordService storageRecordService;

    /**
     * 登录
     */
    @RequestMapping(value = {"", "/login"})
    public String Login(HttpSession session, Model model, String account, String password) {
        SysUser login = sysUserService.login(account, password);
        if (login != null) {
            /**
             * 登录者的信息
             * */
            session.setAttribute("userSession", login);
            /**
             * 角色
             * */
            List<SysRole> roleList = sysRoleService.selectByList();
            session.setAttribute("roleList", roleList);
            /**
             * 供货商
             * */
            List<Supplier> suppliers = supplierServlet.selectList();
            session.setAttribute("supplierList", suppliers);
            return "/WEB-INF/jsp/frame.jsp";
        } else {
            model.addAttribute("error", "用户名或密码错误!");
            return "/WEB-INF/jsp/login.jsp";
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String Logout(HttpSession session) {
        session.invalidate();
        return "/WEB-INF/jsp/login.jsp";
    }

    /**
     * sysUser
     */
    //添加
    @RequestMapping("/sys/user/add")
    protected String UserAdd(@RequestParam(value = "idPic", required = false) MultipartFile multipartFile1,
                             @RequestParam(value = "workPic", required = false) MultipartFile multipartFile2,
                             SysUser sysUser, Model model) {
        String idPic = "";
        String fileName = multipartFile1.getOriginalFilename();
        if (fileName != null && !fileName.equals("")) {
            try {
                fileName=System.currentTimeMillis()+""+multipartFile1.getOriginalFilename();
                String path = System.getProperty("user.dir").replace("bin", "webapps") + "/upload/";
                File file = new File(path, fileName);
                multipartFile1.transferTo(file);
                idPic+= fileName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sysUser.setIdPice(idPic);

        String workPic = "";
        String fileName2 = multipartFile2.getOriginalFilename();
        if (fileName2 != null && !fileName2.equals("")) {
            try {
                fileName2=System.currentTimeMillis()+""+multipartFile2.getOriginalFilename();
                String path = System.getProperty("user.dir").replace("bin", "webapps") + "/upload/";
                File file = new File(path, fileName2);
                multipartFile2.transferTo(file);
                workPic+= fileName2;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sysUser.setWorkPice(workPic);
        sysUser.setCreatedTime(new Date());

        int insert = sysUserService.insert(sysUser);
        String msg = insert > 0 ? "添加成功!" : "添加失败!";

        model.addAttribute("msg", msg);
        return "forward:/sys/user/list";
    }

    //删除
    @RequestMapping("/sys/user/del")
    @ResponseBody
    public Object UserDelete(int userid) {
        String delResult = null;
        int delete = 0;
        try {
            delete = sysUserService.delete(userid);
            delResult = delete > 0 ? "true" : "false";
        } catch (Exception e) {
            e.printStackTrace();
            delResult = "notexist";
        } finally {
            Map map = new HashMap();
            map.put("delResult", delResult);

            return map;
        }
    }


    //查询User全部信息
    @RequestMapping("/sys/user/list")
    public String UserList(@RequestParam(defaultValue = "1") int pageIndex,
                           String queryRealName, Integer queryRoleId,
                           Model model) {
        Page<SysUser> page = new Page<>();
        //设置第几页
        page.setCurrentPageNo(pageIndex);
        page.setList(sysUserService.getUserListByParams(queryRealName, queryRoleId, page.getCurrentPageNo(), page.getPageSize()));
        page.setTotalCount(sysUserService.count(queryRealName, queryRoleId));

        model.addAttribute("queryRoleId", queryRoleId);
        model.addAttribute("queryRealName", queryRealName);
        model.addAttribute("page", page);

        return "/WEB-INF/jsp/sysUser/list.jsp";
    }

    //查询密码
    @RequestMapping("/sys/user/checkOldPwd")
    @ResponseBody
    public Object checkOldPwd(String oldPassword, HttpSession session) {

        SysUser userSession = (SysUser) session.getAttribute("userSession");
        String account = userSession.getAccount();

        SysUser login = sysUserService.login(account, oldPassword);
        String result = null;
        if (oldPassword == null && oldPassword.equals("")) {        //旧密码为空
            result = "error";
        } else if (account == null) {               //当前用户session过期，请重新登录
            result = " sessionerror";
        } else if (login == null) {                 //旧密码输入不正确
            result = "false";
        } else if (login != null) {                 //旧密码输入正确
            result = "true";
        }

        Map map = new HashMap();
        map.put("result", result);

        return map;
    }

    //前往添加页面
    @RequestMapping("/sys/user/toAdd")
    public String toAdd() {
        return "/WEB-INF/jsp/sysUser/add.jsp";
    }

    //前往修改密码页面
    @RequestMapping("/sys/user/toUpdatePwd")
    public String toUpdatePwd() {
        return "/WEB-INF/jsp/sysUser/updatePassword.jsp";
    }

    //前往修改信息页面
    @RequestMapping("/sys/user/toUpdate")
    public String toUpdate(Integer uid, Model model) {
        SysUser sysUser = sysUserService.selectById(uid);
        model.addAttribute("sysUser", sysUser);
        return "/WEB-INF/jsp/sysUser/update.jsp";
    }

    //执行修改密码
    @RequestMapping("/user/savePassword")
    public String savePassword(Integer id, String newPassword, String oldPassword, Model model) {

        int i = sysUserService.UpdatePwd(newPassword, oldPassword, id);
        String msg = i > 0 ? "修改成功" : "修改失败";

        model.addAttribute("msg", msg);
        return "/WEB-INF/jsp/frame.jsp";
    }

    //执行修改信息
    @RequestMapping("/sys/user/update")
    public String update(@RequestParam(value = "idPic", required = false) MultipartFile multipartFile1,
                         @RequestParam(value = "workPic", required = false) MultipartFile multipartFile2,
                         SysUser sysUser, Model model) {
        String idPic = "";
        String fileName = multipartFile1.getOriginalFilename();
        if (fileName != null && !fileName.equals("")) {
            try {
                fileName=System.currentTimeMillis()+""+multipartFile1.getOriginalFilename();
                String path = System.getProperty("user.dir").replace("bin", "webapps") + "/upload/";
                File file = new File(path, fileName);
                multipartFile1.transferTo(file);
                idPic+= fileName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sysUser.setIdPice(idPic);
        String workPic = "";
        String fileName2 = multipartFile2.getOriginalFilename();
        if (fileName2 != null && !fileName2.equals("")) {
            try {
                fileName2=System.currentTimeMillis()+""+multipartFile1.getOriginalFilename();
                String path = System.getProperty("user.dir").replace("bin", "webapps") + "/upload/";
                File file = new File(path, fileName2);
                multipartFile2.transferTo(file);
                workPic+= fileName2;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sysUser.setWorkPice(workPic);

        sysUser.setUpdatedTime(new Date());
        int update = sysUserService.updateXX(sysUser);
        String msg = update > 0 ? "修改成功!" : "修改成功!";
        model.addAttribute("msg", msg);
        return "forward:/sys/user/list";
    }

    //验证
    @RequestMapping("/sys/user/userExist")
    @ResponseBody
    public Object userExist(String account) {
        SysUser user = null;
        String exist = null;
        String msg = null;
        try {
            user = sysUserService.selectAccount(account);
            exist = user == null ? "0" : "1";
        } catch (Exception e) {
            //输出异常
            e.printStackTrace();
            //获取到异常
            msg = e.getMessage();
            exist = "-1";
        }
        Map map = new HashMap();
        map.put("exist", exist);
        map.put("msg", msg);

        return map;
    }

    //单查
    @RequestMapping("/sys/user/view")
    public String view(Model model, Integer userid) {
        SysUser sysUser = sysUserService.selectById(userid);
        model.addAttribute("sysUser", sysUser);
        return "/WEB-INF/jsp/sysUser/view.jsp";
    }

    /**
     * 上面是SysUser的代码
     * ------------
     * 下面是SysRole的代码
     * */

    /**
     * SysRole
     */

    //查询全部
    @RequestMapping("/sys/role/list")
    public String RoleList(Model model) {
        List<SysRole> list = sysRoleService.selectByList();
        model.addAttribute("roleList", list);
        return "/WEB-INF/jsp/sysRole/list.jsp";
    }

    //前往添加
    @RequestMapping("/sys/role/toAdd")
    public String roleToAdd() {
        return "/WEB-INF/jsp/sysRole/add.jsp";
    }

    //执行添加
    @RequestMapping("/sys/role/add")
    public String roleAdd(SysRole sysRole, Model model) {
        sysRole.setCreatedTime(new Date());

        int insert = sysRoleService.insert(sysRole);
        String msg = insert > 0 ? "添加成功!" : "添加失败!";

        if (insert > 0) {
            model.addAttribute("msg", msg);
            return "/sys/role/list";
        } else {
            model.addAttribute("msg", msg);
            return "/WEB-INF/jsp/sysRole/add.jsp";
        }
    }

    //执行删除
    @RequestMapping("/sys/role/del")
    @ResponseBody
    public Object roleDel(int id) {
        String delResult = null;
        SysRole sysRole = sysRoleService.selectById(id);
        if (sysRole != null) {
            int delete = sysRoleService.delete(id);
            delResult = delete > 0 ? "true" : "false";
        } else {
            delResult = "notexist";
        }
        Map map = new HashMap();
        map.put("delResult", delResult);
        return map;
    }

    //前往修改
    @RequestMapping("/sys/role/toUpdate")
    public String roleToUpdate(int id, Model model) {
        SysRole sysRole = sysRoleService.selectById(id);
        model.addAttribute("sysRole", sysRole);
        return "/WEB-INF/jsp/sysRole/update.jsp";
    }

    //执行修改
    @RequestMapping("/sys/role/update")
    public String roleUpdate(SysRole sysRole, Integer userId, Model model) {
        sysRole.setUpdatedUserId((long) userId);
        sysRole.setUpdatedTime(new Date());
        int update = sysRoleService.update(sysRole);
        String msg = update > 0 ? "修改成功!" : "修改失败!";
        if (update > 0) {
            model.addAttribute("msg", msg);
            return "forward:/sys/role/list";
        } else {
            model.addAttribute("msg", msg);
            return "/WEB-INF/jsp/sysRole/update.jsp";
        }
    }

    //单查
    @RequestMapping("/sys/role/codeExist")
    @ResponseBody
    public Object roleCodeExist(String code) {
        int exist = -1;
        if (code != null && !code.equals("")) {
            try {
                SysRole sysRole = sysRoleService.selectByCode(code);
                exist = sysRole == null ? 0 : 1;
            } catch (Exception e) {
                e.printStackTrace();
                exist = -1;
            }
        }
        Map map = new HashMap();
        map.put("exist", exist);

        return map;
    }

    /**
     * 上面是SysRole的代码
     * ------------
     * 下面是Supplier的代码
     */

    /**
     * Supplier
     */
    //删除
    @RequestMapping("/sys/supplier/del")
    @ResponseBody
    public Object SupplierDel(int id) {
        String delResult = "无";
        Supplier supplier = supplierServlet.selectById(id);
        if (supplier != null) {
            int delete = supplierServlet.delete(id);
            delResult = delete > 0 ? "true" : "false";
        }
        Map map = new HashMap();
        map.put("delResult", delResult);

        return map;
    }

    //执行添加
    @RequestMapping("/sys/supplier/add")
    public String supplierAdd(@RequestParam(value = "attachs", required = false) MultipartFile[] multipartFiles,
                              Supplier supplier, long uid, Model model) {
        String license = "";
        String institution = "";
        System.out.println(multipartFiles.length);
        for (int i = 0; i < multipartFiles.length; i++) {
            System.out.println(i);
            String fileName = multipartFiles[i].getOriginalFilename();
            if (fileName != null && fileName != "") {
                try {
                    String path = System.getProperty("user.dir").replace("bin", "webapps") + "/upload/";
                    fileName = System.currentTimeMillis() + "_" + multipartFiles[i].getOriginalFilename();
                    File file = new File(path, fileName);
                    multipartFiles[i].transferTo(file);
                    if (i == 0) {
                        license = fileName;
                    } else {
                        institution = fileName;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(license + "\t" + institution);
        supplier.setLicense(license);
        supplier.setInstitution(institution);

        supplier.setUpdatedUserId(uid);
        supplier.setCreatedTime(new Date());
        int insert = supplierServlet.insert(supplier);
        String msg = insert > 0 ? "添加成功!" : "添加失败!";
        if (insert > 0) {
            model.addAttribute("msg", msg);
            return "forward:/sys/supplier/list";
        } else {
            model.addAttribute("msg", msg);
            return "/WEB-INF/jsp/supplier/add.jsp";
        }
    }

    //查询全部
    @RequestMapping("/sys/supplier/list")
    public String supplierList(String querySupCode, String querySupName,
                               @RequestParam(defaultValue = "1") int pageIndex, Model model) {
        Page<Supplier> page = new Page<>();
        page.setCurrentPageNo(pageIndex);
        int count = supplierServlet.count(querySupCode, querySupName);
        page.setTotalCount(count);
        List<Supplier> list = supplierServlet.selectPageList(querySupCode, querySupName, page.getCurrentPageNo(), page.getPageSize());
        page.setList(list);

        model.addAttribute("querySupCode", querySupCode);
        model.addAttribute("querySupName", querySupName);
        model.addAttribute("page", page);
        return "/WEB-INF/jsp/supplier/list.jsp";
    }

    //单查
    @RequestMapping("/sys/supplier/view")
    public String supplierView(int id, Model model) {
        Supplier supplier = supplierServlet.selectById(id);
        model.addAttribute("supplier", supplier);
        return "/WEB-INF/jsp/supplier/view.jsp";
    }

    //前往添加
    @RequestMapping("/sys/supplier/toAdd")
    public String supplierToAdd() {
        return "/WEB-INF/jsp/supplier/add.jsp";
    }

    //前往修改
    @RequestMapping("/sys/supplier/toUpdate")
    public String supplierToUpdate(int id, Model model) {
        Supplier supplier = supplierServlet.selectById(id);
        model.addAttribute("supplier", supplier);
        return "/WEB-INF/jsp/supplier/update.jsp";
    }

    //执行修改
    @RequestMapping("/supplier/update")
    public String supplierUpdate(@RequestParam(value = "attachs", required = false) MultipartFile[] multipartFiles,
                                 Supplier supplier, long uid, long id, Model model) {
        String license = "";
        String institution = "";
        System.out.println(multipartFiles.length);
        for (int i = 0; i < multipartFiles.length; i++) {
            String fileName = multipartFiles[i].getOriginalFilename();
            if (fileName != null && fileName != "") {
                try {
                    String path = System.getProperty("user.dir").replace("bin", "webapps") + "/upload/";
                    fileName = System.currentTimeMillis() + "_" + multipartFiles[i].getOriginalFilename();
                    File file = new File(path, fileName);
                    multipartFiles[i].transferTo(file);
                    if (i == 0) {
                        license = fileName;
                    } else {
                        institution = fileName;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        supplier.setLicense(license);
        supplier.setInstitution(institution);

        supplier.setId(id);
        supplier.setUpdatedUserId(uid);
        supplier.setUpdatedTime(new Date());
        int update = supplierServlet.update(supplier);
        String msg = update > 0 ? "修改成功!" : "修改失败!";
        if (update > 0) {
            model.addAttribute("msg", msg);
            return "forward:/sys/supplier/list";
        } else {
            model.addAttribute("msg", msg);
            return "/WEB-INF/jsp/supplier/update.jsp";
        }
    }

    /**
     * 上面是Supplier的代码
     * ------------
     * 下面是StorageRecord的代码
     */

    /**
     * StorageRecord
     */

    //查询全部
    @RequestMapping("/sys/storageRecord/list")
    public String storageRecordList(@RequestParam(defaultValue = "1") int pageIndex, String queryGoodsName, Long querySupplierId,
                                    Integer queryPayStatus, Model model) {
        Page<StorageRecord> page = new Page();
        page.setCurrentPageNo(pageIndex);
        page.setTotalCount(storageRecordService.count(querySupplierId, queryPayStatus, queryGoodsName));

        List<StorageRecord> list = storageRecordService.getPageStorageRecord(
                querySupplierId, queryPayStatus, queryGoodsName, page.getCurrentPageNo(), page.getPageSize());
        page.setList(list);

        model.addAttribute("page", page);
        model.addAttribute("queryGoodsName", queryGoodsName);
        model.addAttribute("querySupplierId", querySupplierId);
        model.addAttribute("queryPayStatus", queryPayStatus);
        return "/WEB-INF/jsp/storageRecord/list.jsp";
    }

    //单查
    @RequestMapping("/sys/storageRecord/view")
    public String storageRecordView(int id, Model model) {
        StorageRecord byId = storageRecordService.getById(id);
        model.addAttribute("storageRecord", byId);
        return "/WEB-INF/jsp/storageRecord/view.jsp";
    }

    //执行添加
    @RequestMapping("/sys/storageRecord/add")
    public String storageRecordAdd(long user, StorageRecord storageRecord) {
        storageRecord.setCreatedUserId(user);
        storageRecord.setCreatedTime(new Date());

        int insert = storageRecordService.insert(storageRecord);
        String msg = insert > 0 ? "添加成功!" : "添加失败!";
        if (insert > 0) {
            System.out.println(msg);
        } else {
            System.out.println(storageRecord);
        }
        if (insert > 0) {
            return "forward:/sys/storageRecord/list";
        } else {
            return "/WEB-INF/jsp/storageRecord/add.jsp";
        }
    }

    //删除
    @RequestMapping("/sys/storageRecord/del")
    @ResponseBody
    public Object storageRecordDel(int id) {
        String delResult = null;
        StorageRecord byId = storageRecordService.getById(id);
        if (byId != null) {
            int delete = storageRecordService.delete(id);
            if (delete > 0) {
                delResult = "true";
            } else {
                delResult = "false";
            }
        } else {
            delResult = "notexist";
        }
        Map map = new HashMap();
        map.put("delResult", delResult);

        return map;
    }

    //执行修改
    @RequestMapping("/sys/storageRecord/update")
    public String storageRecordUpdate(int id, long user, StorageRecord storageRecord, Model model) {

        storageRecord.setUpdatedUserId(user);
        storageRecord.setUpdatedTime(new Date());
        storageRecord.setId((long) id);

        int update = storageRecordService.update(storageRecord);
        String msg = update > 0 ? "修改成功!" : "修改失败!";
        if (update > 0) {
            model.addAttribute("msg", msg);
            return "forward:/sys/storageRecord/list";
        } else {
            model.addAttribute("msg", msg);
            return "/sys/storageRecord/toUpdate";
        }
    }

    //前往修改
    @RequestMapping("/sys/storageRecord/toUpdate")
    public String doGet(int id, Model model) {
        StorageRecord byId = storageRecordService.getById(id);
        model.addAttribute("storageRecord", byId);
        return "/WEB-INF/jsp/storageRecord/update.jsp";
    }

    //前往添加
    @RequestMapping("/sys/storageRecord/toAdd")
    public String storageRecordToAdd() {
        return "/WEB-INF/jsp/storageRecord/add.jsp";
    }

}
